<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import {
    rolePageService, roleUpdateService, roleByIdService, menuListService,
    roleDeleteByIdService, roleAddService, roleUpdateAssignmentService, roleQueryAssignmentService
} from '@/api/user'
// 查询条件
const search = ref({})

// 当前角色ID
const currentRoleId = ref(null)

// 树形结构配置
const defaultProps = {
    children: 'children',
    label: 'name'
}

// 添加树组件引用定义
const treeRef = ref(null)

// 树形数据
const treeData = ref([])

// 数据列表
const tableData = ref([]);

// 编辑表单数据
const dialogForm = ref([])

// 多选
const selectedIds = ref([])

// 分页
// 当前页码
const currentPage = ref(1);
// 每页数量
const pageSize = ref(10);
// 总数
const total = ref(0);

// 状态选项
const statusOptions = [
    { label: '启用', value: true },
    { label: '禁用', value: false }
];

// 编辑表单显隐
const dialogVisible = ref(false)

// 菜单表单显隐
const dialogMenuVisible = ref(false)

// 构建树形数据
const buildTree = (data, parentId = 0, level = 0) => {
    return data
        .filter(item => item.parentId == parentId) // 修正字段名
        .map(item => ({
            ...item,
            level: level, // 同步 level 字段
            children: buildTree(data, item.id, level + 1)
        }))
}

onMounted(() => {
    handleSearch()
})

// 查询
const handleSearch = async () => {
    search.value.pageSize = pageSize.value;
    console.log(search.value);
    const result = await rolePageService(search.value)
    tableData.value = result.data.list
    total.value = parseInt(result.data.total)
}

// 清空条件
const clearSearch = () => {
    search.value = {}
    handleSearch()
}

// 获取选择列表
const handleSelectionChange = (selection) => {
    selectedIds.value = selection.map(item => item.id);
};

// 添加
const handleAdd = async () => {
    dialogVisible.value = true;
    dialogForm.value = {
        name: '',
        description: '',
        userCount: '',
        status: ''
    }    
}

// 编辑
const handleEdit = async (id) => {
    const result = await roleByIdService(id);
    const data = result.data;

    // 清空
    dialogForm.value = {}

    // 深度拷贝用户数据
    dialogForm.value = data

    dialogVisible.value = true;
}

// 处理菜单分配
const handleMenuEdit = async (id) => {

    currentRoleId.value = id

    // 获取角色菜单权限
    const assignmentResult = await roleQueryAssignmentService(id)
    const roleMenus = assignmentResult.data?.menuIds || []
    
    // 获取完整菜单数据
    const menuResult = await menuListService()
    // 构建树形结构并统一数据类型
    treeData.value = buildTree(menuResult.data.map(item => ({
        ...item,
        id: String(item.id),      // 统一转为字符串类型
        parentId: String(item.parentId)
    })))
    
    dialogMenuVisible.value = true
    
    // 延迟设置选中状态
    nextTick(() => {
        // 添加空值保护和类型校验
        if (treeRef.value?.setCheckedKeys) {
            // 确保参数为数组类型并统一字符串类型
            const menuIds = Array.isArray(roleMenus) 
                ? roleMenus.map(String) 
                : [String(roleMenus)]
                
            treeRef.value.setCheckedKeys(menuIds)
        }
        
    })
}

// 保存菜单分配
const confirmSelection = async () => {
    try {
        // 添加空值保护和类型校验
        if (!treeRef.value?.getCheckedKeys) {
            ElMessage.error('权限组件未正确初始化')
            return
        }
        
        // 获取选中的菜单ID并确保字符串类型
        const selectedMenus = treeRef.value.getCheckedKeys().map(String)
        console.log(selectedMenus);
        
        
        // 调用接口保存权限
        await roleUpdateAssignmentService({
            id: currentRoleId.value, 
            assignment: {
                menuIds: selectedMenus
            }
        })
        
        ElMessage.success('权限分配成功')
        dialogMenuVisible.value = false
        handleSearch()
    } catch (error) {
        ElMessage.error('权限分配失败：' + error.message)
    }
}

// 保存
const saveEdit = async () => {

    try {
        if (dialogForm.value.id) {
            // 更新用户信息
            await roleUpdateService(dialogForm.value);
            ElMessage.success('更新成功!');
        } else {
            // 创建新用户
            await roleAddService(dialogForm.value);
            ElMessage.success('添加成功!');
        }

        dialogVisible.value = false;
        handleSearch();
    } catch (error) {
        ElMessage.error('操作失败：' + error.message);
    }
}



// 删除
const handleDelete = async (id) => {
    // 删除
    ElMessageBox.confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        // 确定删除
        await roleDeleteByIdService(id);
        ElMessage.success('删除成功!');
        handleSearch();
    }).catch(() => {
        // 取消删除
        ElMessage.info('已取消删除');
    })
}

// 每页展示记录数变化
const handleSizeChange = (val) => {
    // 同步更新 pageSize
    pageSize.value = val;
    // 同步更新搜索参数
    search.value.pageSize = val;
    console.log(`每页 ${val} 条`);
    handleSearch();
}
// 页码变化时触发
const handleCurrentChange = (val) => {
    // 同步更新 currentPage
    currentPage.value = val;
    // 同步更新搜索参数
    search.value.pageNum = val;
    console.log(`当前页: ${val}`);
    handleSearch();
}

// 处理开关变化
const handleSwitchChange = async (row) => {
    await roleUpdateService({
        id: row.id,
        status: row.status
    })
    ElMessage.success('状态更新成功')
}
</script>

<template>
    <div>
        <!-- 数据列表标题和添加按钮 -->
        <div class="card-header">
            <el-card shadow="never">
                <!-- 筛选搜索区域 -->
                <el-form :model="search" label-width="100px">
                    <el-row :gutter="15">
                        <el-col :span="5">
                            <el-form-item label="输入搜索：">
                                <el-input v-model="search.name" placeholder="角色名称"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item label="状态：">
                                <el-select v-model="search.status" placeholder="全部" style="width: 100%">
                                    <el-option label="全部" value=""></el-option>
                                    <el-option label="正常" value="1"></el-option>
                                    <el-option label="禁用" value="0"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <el-col style="margin: 0 0 0 37%;" :span="5">
                            <el-button type="info" @click="clearSearch">清空</el-button>
                            <el-button type="primary" @click="handleSearch">查询</el-button>
                            <el-button type="success" @click="handleAdd">添加</el-button>
                        </el-col>
                    </el-row>
                </el-form>
            </el-card>
        </div>

        <!-- 数据表格 -->
        <el-table :data="tableData" @selection-change="handleSelectionChange" class="table-list">
            <el-table-column align="center" label="编号" prop="id" width="120"></el-table-column>
            <el-table-column align="center" label="角色名称" prop="name" width="250"></el-table-column>
            <el-table-column align="center" label="描述" prop="description" width="250"></el-table-column>
            <el-table-column align="center" label="用户数" prop="userCount" width="200"></el-table-column>
            <el-table-column align="center" label="添加时间" prop="createDate" width="200"></el-table-column>
            <el-table-column align="center" label="状态" prop="status" width="120">
                <template #default="scope">
                    <el-switch v-model="scope.row.status"
                        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                        @change="handleSwitchChange(scope.row)" />
                </template>
            </el-table-column>
            <el-table-column align="center" label="操作">
                <template align="center" #default="scope">
                    <el-button type="primary" text @click="handleMenuEdit(scope.row.id)">分配菜单</el-button>
                    <!-- <el-button type="primary" text @click="handleEdit(scope.row.id)">分配资源</el-button> -->
                    <el-button type="primary" text @click="handleEdit(scope.row.id)">编辑</el-button>
                    <el-button type="danger" text @click="handleDelete(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
            :page-sizes="[5, 10, 15, 20, 30, 50, 100]" size="default" :background="true"
            layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
    </div>
    <!-- 编辑表单 -->
    <el-dialog v-model="dialogVisible" title="编辑用户" width="37%">
        <el-form :model="dialogForm" label-width="120px" label-position="right" :rules="rules" ref="formRef">
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="角色名称：" prop="name">
                        <el-input v-model="dialogForm.name" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="描述信息：" prop="description">
                        <el-input v-model="dialogForm.description" type="textarea" :rows="3" show-word-limit
                            maxlength="200" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="状态：" prop="status">
                        <el-select v-model="dialogForm.status" placeholder="请选择">
                            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="saveEdit">确定</el-button>
            </span>
        </template>
    </el-dialog>

    <!-- 菜单分配 -->
    <el-dialog title="权限分配" v-model="dialogMenuVisible" width="20%">
        <!-- 树形控件 -->
        <el-tree 
            default-expand-all
            :data="treeData" 
            show-checkbox 
            node-key="id" 
            :props="defaultProps" 
            ref="treeRef"
        ></el-tree>

        <!-- 确认和取消按钮 -->
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogMenuVisible = false">取 消</el-button>
                <el-button type="primary" @click="confirmSelection">确 定</el-button>
            </span>
        </template>
    </el-dialog>

</template>

<style scoped>
/* card 样式 */
.card-header {
    width: 96%;
    margin: 0 0 0 2%;
}

/* card标题栏样式 */
.card-title {
    margin-right: 80%;
}

/* 表格样式 */
.table-list {
    width: 96%;
    margin: 3vh 0 3vh 2%;

}

.el-pagination {
    margin: 0 0 0 35% !important;
}

</style>